/**
 * <pre>
 * Title: 		SMSListUtil.java
 * Project: 	AgentPortal_1.13.x
 * Author:		linriqing
 * Create:	 	2009-3-24 下午04:18:09
 * Copyright: 	Copyright (c) 2009
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.itfinoss.util.SignatureHelper;

/**
 * <pre>
 * 短消息工具
 * </pre>
 * @author LMM
 * @version 1.0, 2012-3-5
 */
public class SMSUtil
{
	/**
	 * 短信接口参数名
	 */
	public static final String PARANAME_CONTENT = "content";

	public static final String PARANAME_DIGEST = "digest";

	public static final String PARANAME_PRIORITY = "priority";

	public static final String PARANAME_STATE = "state";

	public static final String PARANAME_TYPE = "type";

	public static final String PARANAME_MOBILE = "mobile";

	public static final String PARANAME_ISFIRST = "isfirst";

	public static final String PARANAME_USERID = "userId";

	public static final String PARANAME_TIME = "time";

	public static final int SENDTYPE = 1;

	public static final int SCHEDULED_SENDTYPE = 2;

	public static final String SMSEQ = "=";

	public static final String SMSAND = "&";

	private final static Log logger = LogFactory.getLog(SMSUtil.class);

	/**
	 * 系统参数名-短信接口密钥
	 */
	public static final String SMSPORT_KEY = "ms306.smsportkey";

	/**
	 * 系统参数名-短信接口地址
	 */
	public static final String SMSPORT_URL = "ms306.smsporturl";

	/**
	 * 系统参数名-短信接口用户名
	 */
	public static final String SMSPORT_USERID = "ms306.smsportuserid";

	private static String doPost(String urlStr, String parameter, String requestEncode)
	{
		StringBuffer result = new StringBuffer();
		HttpURLConnection conn = null;
		try
		{
			conn = (HttpURLConnection) new URL(urlStr).openConnection();
			// 超时时间5秒
			conn.setConnectTimeout(5000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), requestEncode);
			out.write(parameter);// 这里组织域信息
			out.flush();
			out.close();
			InputStream is = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, requestEncode));
			String line = null;
			while ((line = reader.readLine()) != null)
			{
				result.append(line + "\n\r");
			}
			is.close();
			conn.disconnect();
			reader.close();
		}
		catch (Exception e)
		{
			logger.error(e);
		}
		finally
		{
			if (conn != null)
			{
				conn.disconnect();
			}
		}
		return result.toString();
	}

	/**
	 * 发送短信
	 * @param content 内容
	 * @param mobile 手机号
	 * @param isfrist 立即发送(0)
	 * @param priority 发送短信等级,共5级(1~5)一般用3
	 * @param type 发送短信的类型(1->普通,2->通知,3->促销,4->警告)
	 * @return 0->成功,1->失败
	 */
	public static boolean doSendSMS(String content, String mobile, Integer type, Integer priority)
	{
		if (isNotNull(content) && isNotNull(mobile) && isNotNull(priority) && isNotNull(type))
		{
			String smsporturl =null; //MS306Config.getValue(SMSUtil.SMSPORT_URL);
			String userid = null;//MS306Config.getValue(SMSUtil.SMSPORT_USERID);
			String key = null;//MS306Config.getValue(SMSUtil.SMSPORT_KEY);
			String transMessage = createString(userid,key,content, mobile, priority, type);
			if (isNotNull(smsporturl)&&isNotNull(userid)&&isNotNull(key))
			{
				String smsRsp = SMSUtil.doPost(smsporturl, transMessage, "UTF-8");
				if (smsRsp.trim().equalsIgnoreCase("0"))
				{
					// 短信发送成功
					logger.info("短信发送成功!对方手机[" + mobile + "],发送内容:" + content);
					return true;
				}
				else
				{// 短信发送失败
					logger.info("短信发送失败!对方手机[" + mobile + "],具体失败原因需要向短信服务端查询");
					return false;
				}

			}
			else
			{
				logger.error("缺少短信服务端配置!短信发送失败!");
				return false;
			}
		}
		else
		{
			logger.error("短信请求数据不完整!短信发送失败!");
			return false;
		}
	}

	/**
	 * 
	 * <pre>
	 * 组织信息
	 * </pre>
	 * @param content 内容
	 * @param mobile 手机号
	 * @param priority 优先级 (1~5)值越大优先级越高
	 * @param type 类型
	 * @return
	 */
	private static String createString(String userid ,String key ,String content, String mobile,
			Integer priority, Integer type)
	{
		String sendstate="1";
		StringBuilder builder = new StringBuilder();
		String digestSource = key + mobile + content + priority + sendstate + type;
		String digest = SignatureHelper.generateMD5Signture(digestSource, "UTF-8");
		builder.append(PARANAME_DIGEST + SMSEQ + digest + SMSAND);
		builder.append(PARANAME_USERID + SMSEQ + userid + SMSAND);
		builder.append(PARANAME_ISFIRST + SMSEQ + 0 + SMSAND);
		builder.append(PARANAME_MOBILE + SMSEQ + mobile + SMSAND);
		builder.append(PARANAME_CONTENT + SMSEQ + content + SMSAND);
		builder.append(PARANAME_PRIORITY + SMSEQ + priority + SMSAND);
		builder.append(PARANAME_STATE + SMSEQ + 1 + SMSAND);
		builder.append(PARANAME_TYPE + SMSEQ + type);
		return builder.toString();
	}

	private static boolean isNotNull(Object str)
	{
		if (str != null && str.toString().trim().length() > 0)
			return true;
		else
			return false;
	}

	public static void main(String[] args) throws Exception
	{
		//
		String mobile = "13585760663";
	//	String isResumeStr="自动续投";
		String content = "您办理的双色球定投2。【重庆福彩】";
		// SMSUtil.doSendSMS(content, mobile, 1, 3, 1);

		String smsporturl = "http://storeoss.happycp.com/servlet/smsrecieve";
		//String smsporturl = "http://localhost:8080/servlet/smsrecieve";
		String userid = "1";
		String key = "CS001";
		String transMessage = createString(userid,key,content, mobile,3, 4);
		if ((smsporturl != null) && (smsporturl.length() > 0))
		{
			String smsRsp = SMSUtil.doPost(smsporturl, transMessage, "UTF-8");
			System.out.println(smsRsp.trim());
			System.out.println(smsRsp.trim().equalsIgnoreCase("0"));
			SMSUtil.logger.info("发送事件通知到手机号码{" + mobile + "}响应消息：" + smsRsp);

		}

	}
}
